import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { message, Card, Form, Radio, Popconfirm, Modal, Icon, DatePicker, Select, Row, Col, Input, AutoComplete } from 'antd';
import BoxList from '../BoxList';
import styles from './styles.less';
import moment from 'moment';

import AddRelationerForm from '@/components/AddRelationerForm';
import RenderAuthorized from '@/components/Authorized';

const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;
const { Option: AutoCompleteOption } = AutoComplete;
const RadioGroup = Radio.Group;

@connect(({ user, tiDanState, relationer, mbl, port }) => ({
  tiDanStates: tiDanState.list,
  relationers: relationer.list,
  ports: port.list,
  mbl: mbl.current,
  cUser: user.currentUser,
}))
@Form.create()
class Comp extends PureComponent {

  state = {
    visible: false,
    addRelVisible: false,
    list: [],
    current: undefined,

    shipper: undefined,
    consignee: undefined,
    notifyParty: undefined,
  };

  componentDidMount() {
    const { bill } = this.props;
    this.setCurrent(bill);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.bill !== this.props.bill) {
      this.setCurrent(nextProps.bill);
    }
  }

  setCurrent(bill) {
    const { relationers } = this.props;
    if (bill) {
      this.setState({
        current: {
          ...bill,
          isHBL: bill.mblId > 0
        },
        shipper: relationers.find(r => r.id === bill.shipperId),
        consignee: relationers.find(r => r.id === bill.consigneeId),
        notifyParty: relationers.find(r => r.id === bill.notifyPartyId)
      });
    }
  }

  handleRelSelected = (relType, value) => {
    const { relationers } = this.props;
    const rel = relationers.find(r => r.id === Number(value));
    // 可为undefined: 如果是undefined，那么就是没有选中任何一个，可能是空的，也可能是新加了内容.
    if (relType === 1) {
      this.setState({ shipper: rel });
    } else if (relType === 2) {
      this.setState({ consignee: rel });
    } else if (relType === 3) {
      this.setState({ notifyParty: rel });
    }
  }

  handleSubmit(e) {
    e.preventDefault();
    const { shipper, consignee, notifyParty } = this.state;
    const { mbl, form } = this.props;

    let { current: vm } = this.state;

    const initVal = {
      id: 0,
      mblId: mbl.id,
      typeOfPayment: 1,
      tiDanStateId: 0,
    }

    var isValid = true;
    // Header FORM
    form.validateFields((err, values) => {
      if (err) {
        isValid = false;
        return;
      }

      vm = {
        ...vm,
        ...values,
        shipper: shipper,
        consignee: consignee,
        notifyParty: notifyParty,
      };

      vm = {
        ...vm,
        shipperId: (shipper && shipper.id && shipper.id) || 0,    // 下拉选择的 => 原先的 => 0
        consigneeId: (consignee && consignee.id && consignee.id) || 0,
        notifyPartyId: (notifyParty && notifyParty.id && notifyParty.id) || 0,
      };

    });

    //  Box FORM
    const { form: boxForm } = this.boxListForm.props;
    boxForm.validateFields((err, values) => {

      console.log("VALUES FROM BOX", values);
      if (err) {
        isValid = false;
        return;
      }
      vm = {
        ...vm,
        boxlist: values,
      }
    });

    if (!isValid)
      return;
      
      console.log("VM", vm);
      
      this.props.onSave(vm);
      
    }
    
  handleAddRelFormSubmit(vm) {
    console.log("REL ADDED...", vm);
    this.setState({ addRelVisible: false });
  }
  
  render() {
    const { form: { getFieldDecorator }, ports, mbl, cUser } = this.props;
    const { tiDanStates, relationers } = this.props;
    const { current, addRelVisible, shipper, consignee, notifyParty, } = this.state;
    
    const suffix = <Icon type="plus" style={{ cursor: 'pointer' }} onClick={() => this.setState({ addRelVisible: true })} />;
    
    const Authorized = RenderAuthorized(cUser.sys_Role.enCode);

    const noLabelFormLayout = {
      labelCol: {
        sm: { span: 0 },
      },
      wrapperCol: {
        sm: { span: 24 },
      },
    };

    const objectNumberEditor = () => {
      const formLayout = {
        labelCol: {
          sm: { span: 7 },
        },
        wrapperCol: {
          sm: { span: 17 },
        },
      };

      const numberFormLayout = {
        labelCol: { sm: { span: 4 }, },
        wrapperCol: { sm: { span: 20 }, },
      };

      const getObjNumber = () => {
        let xp = '';
        if (current) {
          if (!current.isHBL) {
            // 主单 => SO号
            xp = current.so;
          } else {
            // 分单 => ObjectNumber 分单号
            if (current.objectNumber && current.objectNumber.length > 0) {
              xp = current.objectNumber;
            } else {
              xp = this.props.mbl.objectNumber;
            }
          }
        }
        return xp;
      }


      return (
        <Row className={styles.objectNumberRow} style={{ height: '1em', marginBottom: '2em' }}>
          <Col span={19} className={styles.numberCol} style={{ display: 'flex', height: '1px' }}>
            <FormItem label={current && !current.isHBL ? 'MBL' : 'HBL'} {...numberFormLayout}  >
              {getFieldDecorator(`objectNumber`, {
                initialValue: getObjNumber(),
              })(
                <Input style={{ fontStyle: 'italic' }} />
              )}
            </FormItem>
            <FormItem label="状态"  {...formLayout} style={{ marginLeft: '1em' }} >
              {getFieldDecorator('tiDanStateId', {
                initialValue: current && current.tiDanStateId || 0,
              })(
                <Select style={{ minWidth: '100px' }}>
                  {[{ id: 0, objectName: '' }].concat(tiDanStates).map(item => <Option key={item.id} value={item.id} >{item.objectName}</Option>)}
                </Select>
              )}
            </FormItem>
            <FormItem label="付款方式"   {...formLayout} style={{ marginLeft: '2em' }} >
              {getFieldDecorator('typeOfPayment', {
                initialValue: current && current.typeOfPayment || 0,
              })(
                <RadioGroup style={{ width: '300px' }}>
                  {[{ id: 0, objectName: '未确定' }, { id: 1, objectName: '预付' }, { id: 2, objectName: '到付' },].map(item => <Radio key={item.id} value={item.id} >{item.objectName}</Radio>)}
                </RadioGroup>
              )}
            </FormItem>
            <FormItem label="开船日期"   {...formLayout} style={{ marginLeft: '2em' }} >
              {getFieldDecorator('etd', {
                initialValue: mbl && mbl.etd ? moment(mbl.etd) : null,
              })(
                <DatePicker />
              )}
            </FormItem>
          </Col>
          <Col span={5}>
            <div style={{ display: 'flex', float: "right", height: '100%', marginTop: '1em', marginRight: '.5em' }}>
              {this.props.actions}
              <Authorized authority={['SysAdmin', 'SysOperator']} >
                <a style={{ marginLeft: '8px', display: mbl.isLock === 1 ? 'none' : '' }} onClick={(e) => this.handleSubmit(e)} > 保存</a>
              </Authorized>
            </div>
          </Col>
        </Row>
      );
    }

    const headerEditor = () => {

      const sName = () => shipper && shipper.objectName;
      const cName = () => consignee && consignee.objectName;
      const nName = () => notifyParty && notifyParty.objectName;

      const sAddress = () => (current && current.shipperAddress) || (shipper && shipper.address);
      const cAddress = () => (current && current.consigneeAddress) || (consignee && consignee.address);
      const nAddress = () => (current && current.notifyPartyAddress) || (notifyParty && notifyParty.address);

      return (<Form>
        <Row className={styles.sft} style={{ height: '11em' }} >
          <Col span={1} className={styles.leaderCol} style={{ width: '2.2em', paddingTop: '1.6em' }}>发货人</Col>
          <Col span={7}>
            <FormItem label="" {...noLabelFormLayout}>
              {getFieldDecorator('shipperName', {
                initialValue: sName(),
              })(
                <AutoComplete
                  placeholder="名称"
                  autoFocus={true}
                  backfill={true}
                  onChange={(value) => { this.handleRelSelected(1, value) }}
                  filterOption={(inputValue, option) => option.props.children.toUpperCase().trim().indexOf(inputValue.toUpperCase().trim()) !== -1} >
                  {relationers.map((rel) => { return <AutoCompleteOption key={rel.id} value={String(rel.id)} >{rel.objectName}</AutoCompleteOption> })}
                </AutoComplete>
                // <Input suffix={suffix} />
              )}
            </FormItem>
            <FormItem label="" {...noLabelFormLayout} style={{ borderTop: '2px deepskyblue solid' }}>
              {getFieldDecorator('shipperAddress', {
                initialValue: sAddress(),
              })(
                <TextArea placeholder="地址" style={{ height: '7.5em' }} />
              )}
            </FormItem>
          </Col>
          <Col span={1} className={styles.labelCol} style={{ width: '2.2em', paddingTop: '1.6em' }}>收货人</Col>
          <Col span={7}>
            <FormItem label="" {...noLabelFormLayout}>
              {getFieldDecorator('consigneeName', {
                initialValue: cName(),
              })(
                <AutoComplete
                  placeholder="名称"
                  autoFocus={true}
                  backfill={true}

                  onChange={(value) => { this.handleRelSelected(2, value) }}
                  filterOption={(inputValue, option) => option.props.children.toUpperCase().trim().indexOf(inputValue.toUpperCase().trim()) !== -1} >
                  {relationers.map((rel) => { return <AutoCompleteOption key={rel.id} value={String(rel.id)} >{rel.objectName}</AutoCompleteOption> })}
                </AutoComplete>
              )}
            </FormItem>
            <FormItem label="" {...noLabelFormLayout} style={{ borderTop: '2px deepskyblue solid' }}>
              {getFieldDecorator('consigneeAddress', {
                initialValue: cAddress(),
              })(
                <TextArea placeholder="地址" style={{ height: '7.5em' }} />
              )}
            </FormItem>
          </Col>
          <Col span={1} className={styles.labelCol} style={{ width: '2.2em', paddingTop: '1.6em' }}>通知人</Col>
          <Col span={8}>
            <FormItem label="" {...noLabelFormLayout}>
              {getFieldDecorator('notifyPartyName', {
                initialValue: nName(),
              })(
                <AutoComplete
                  placeholder="名称"
                  autoFocus={true}
                  backfill={true}
                  onChange={(value) => { this.handleRelSelected(3, value) }}
                  filterOption={(inputValue, option) => option.props.children.toUpperCase().trim().indexOf(inputValue.toUpperCase().trim()) !== -1} >
                  {relationers.map((rel) => { return <AutoCompleteOption key={rel.id} value={String(rel.id)} >{rel.objectName}</AutoCompleteOption> })}
                </AutoComplete>
              )}
            </FormItem>
            <FormItem label="" {...noLabelFormLayout} style={{ borderTop: '2px deepskyblue solid' }}>
              {getFieldDecorator('notifyPartyAddress', {
                initialValue: nAddress(),
              })(
                <TextArea placeholder="地址" style={{ height: '7.5em' }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row className={styles.vessaRow} style={{ height: '3em' }} >
          <Col span={2} className={styles.leaderCol} style={{ lineHeight: '2.8em' }} >船名航次</Col>
          <Col span={4} >
            <FormItem label="" {...noLabelFormLayout}>
              {getFieldDecorator('shipName', {
                initialValue: mbl ? mbl.shipName : '',
              })(
                <Input placeholder="船名航次" />
              )}
            </FormItem>
          </Col>
          <Col span={2} className={styles.labelCol} style={{ lineHeight: '2.8em' }}>起运港</Col>
          <Col span={4} >
            <FormItem label="" {...noLabelFormLayout}>
              {getFieldDecorator('sourcePort', {
                initialValue: mbl ? mbl.sourcePort : '',
              })(
                <Select
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >
                  {ports.filter(r => r.portType === 1).map(p => (
                    <Option key={p.id}>{p.objectName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={2} className={styles.labelCol} style={{ lineHeight: '2.8em' }}>目的港</Col>
          <Col span={4} >
            <FormItem label="" {...noLabelFormLayout}>
              {getFieldDecorator('targetPort', {
                initialValue: mbl ? mbl.targetPort : '',
              })(
                <Select
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >
                  {ports.filter(r => r.portType === 2).map(p => (
                    <Option key={p.id}>{p.objectName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col span={2} className={styles.labelCol} style={{ lineHeight: '2.8em' }}>目的地</Col>
          <Col span={4} >
            <FormItem label="" {...noLabelFormLayout}>
              {getFieldDecorator('portOfDelivery', {
                initialValue: mbl ? mbl.portOfDelivery : '',
              })(<Input />)}
            </FormItem>
          </Col>
        </Row>
        <Row className={styles.nameAndMarks} style={{ height: '6em' }}>
          <Col span={2} className={styles.leaderCol} style={{ lineHeight: '5.7em' }}>品名</Col>
          <Col span={10} >
            <FormItem label="" {...noLabelFormLayout}>
              {getFieldDecorator('objectName', {
                initialValue: current ? current.objectName : '',
              })(
                <TextArea style={{ height: '5.7em' }} />
              )}
            </FormItem>
          </Col>
          <Col span={2} className={styles.labelCol} style={{ lineHeight: '5.7em' }}>唛头</Col>
          <Col span={10} >
            <FormItem label="" {...noLabelFormLayout}>
              {getFieldDecorator('marks', {
                initialValue: current ? current.marks : '',
              })(
                <TextArea style={{ height: '5.7em' }} />
              )}
            </FormItem>
          </Col>
        </Row>
      </Form>
      );
    };

    return (
      <div className={styles.border} >
        {objectNumberEditor()}
        < div className={styles.container} >
          {headerEditor()}
          < div className={styles.boxList} >
            <BoxList bill={current} getInstance={form => (this.boxListForm = form)} />
          </div>
         
        </div >
        <AddRelationerForm
          visible={addRelVisible}
          onOk={(vm) => this.handleAddRelFormSubmit(vm)}
          onCancel={() => this.setState({ addRelVisible: false, })}
        />
      </div >
    );
  }
}

export default Comp;
